#coding=utf-8

import os
import random

from image.models import Image
from django.conf import settings

def handle_upload_image(user, file,  type):
    if not user or not file:
        return None 
    raw_file = "%d_upload.jpg"%(random.randint(0, 100000))
    store_file_name = os.path.join(settings.IMAGE_UPLOAD_PATH, raw_file);
    try:
        store_file = open(store_file_name, "wb")
        for chunk in file.chunks():
            store_file.write(chunk)        
        store_file.close()
        image = Image(user=user, raw_file=raw_file, type=type)
        image.save()
        return image        
    except Exception, ex:
        print ex
        return None